<template>
  <div class="toast" :class="{ fade: fade, 'fade-out': isClosing }">
    <div class="wrapper" :class="{ fade: fade, 'fade-out': isClosing }">
      {{ message }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  name: 'Toast',
  props: {
    message: {
      type: String,
      required: true
    },
    duration: {
      type: Number,
      default: 2000
    },
    cancelCallback: {
      type: Function,
      required: true
    } 
  },
  setup(props, { emit }) {
    const visible = ref(false)
    const fade = ref(false)
    const isClosing = ref(false)

    const close = () => {
      isClosing.value = true
      fade.value = false
      setTimeout(() => {
        props.cancelCallback()
        emit('close')
      }, 400)
    }

    onMounted(() => {
      visible.value = true
      setTimeout(() => {
        fade.value = true
      }, 0)

      if (props.duration > 0) {
        setTimeout(() => {
          close()
        }, props.duration)
      }
    })

    return {
      visible,
      fade,
      isClosing
    }
  }
}
</script>

<style scoped lang="scss">
@use '../vars.scss';

.toast {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  pointer-events: none;
  
  &.fade {
    transition: all 0.4s;
  }

  .wrapper {
    position: fixed;
    left: 50%;
    top: 30px;
    transform: translate(-50%, -60%);
    padding: 10px 20px;
    background: rgba(0, 0, 0, 0.75);
    border-radius: vars.$border-radius;
    color: #fff;
    font-size: 14px;
    opacity: 0;

    &.fade {
      transition: all 0.4s;
      transform: translate(-50%, -50%);
      opacity: 1;
    }

    &.fade-out {
      transition: all 0.3s;
      transform: translate(-50%, -40%);
      opacity: 0;
    }
  }
}
</style>
